﻿; (function (window, undefined) {
    var LazyLoad = function () {
        var that = this;
        that.lazytags = null;
        that.nowHeight = null;
    }

    LazyLoad.prototype = {
        init: function (opts) {
            var that = this;
            that.bindUI();
            that.getClientArea();
            that.getEleMap(opts.tags);
        },
        //获取需要延时加载的元素
        getEleMap: function (tags) {
            var that = this;
            var tags = document.getElementsByTagName(tags);
            that.lazytags = tags;
        },
        //获取可视区
        getClientArea: function () {
            var that = this;
            var bowserMode = document.compatMode;
            var bowserType;
            var client = document.compatMode == "BackCompat" ? document.body : document.documentElement;
            var sTop = client.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
            that.nowHeight = sTop + window.innerHeight;
        },
        //判断元素是否在可视区内
        inClientArea: function (obj) {
            return obj.offsetTop < this.nowHeight;
        },
        loadImg: function () {
            var that = this;
            for (var i = 0, len = that.lazytags.length; i < len; i++) {
                var ele = that.lazytags[i];
                var source = ele.getAttribute("data-source");
                if (that.inClientArea(ele) && source && ele.getAttribute != source) {
                    ele.setAttribute("src", source);
                }
            }
        },
        addEvent: function (ele, event, fn, bubble) {
            if (ele.attachEvent) {
                ele.attachEvent("on" + event, fn);
            } else {
                bubble == undefined ? false : bubble;
                ele.addEventListener(event, fn, bubble);
            }
        },
        bindUI: function (ele) {
            var that = this;
            var ele = ele || window;
            that.addEvent(ele, "scroll", function () {
                console.log("add")
                that.loadImg();
            }, false);
        }
    };

    window["LazyLoad"] = LazyLoad;
})(window);